<?php
declare (strict_types=1);

namespace app\admin\model\base;

use app\BaseModel;
use job\ThinkQueueJob;
use think\facade\Db;
use think\Model;

/**
 * 系统操作日志
 */
class SysLog extends BaseModel
{
    /**
     * 获取系统日志列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @param string $orderby
     * @return array
     */
    public static function getList(array $where, int $page, int $limit, string $orderby = ''): array
    {
        $data = self::where($where)
            ->order($orderby)
            ->paginate(['list_rows' => $limit, 'page' => $page], false)
            ->toArray();
        return $data;
    }

    /**
     * 处理系统日志
     * @return bool
     */
    public static function handleSysLog(): bool
    {
        //判断是前端用户还是后端用户
        $data['user_id'] = 0;
        if (defined("WS_ADMIN_ID")) {
            $data['user_id'] = WS_ADMIN_ID;
        } elseif (defined("WS_USER_ID")) {
            $data['user_id'] = WS_USER_ID;
        }
        //获取请求的参数
        $request = request();
        $data['method'] = $request->method();
        $data['base_url'] = $request->baseUrl();
        $data['root_url'] = $request->rootUrl();
        $data['ip'] = $request->ip();
        //处理param
        $param = json_encode($request->param(), JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
        $data['data'] = strlen($param) < 2000 ? $param : '数据超长';
        $data['return'] = json_encode([]);
        $data['create_time'] = time();
        //生成唯一字符串
        request()->request_id = $data['request_id'] = uuid();
        //推送至系统日志队列
        ThinkQueueJob::sendMsg('WriteSystemLog', '', $data);
        return true;
    }

    /**
     * 写入系统日志
     * @param array $data
     * @return SysLog|Model
     */
    public static function writeSysLog(array $data): SysLog|Model|bool
    {
        //更新为日志写入mogo
        $date = date('Y-m-d');
//        Db::connect('mongodb')
//            ->table($date)
//            ->insert($data);
//        return true;
        return self::create($data);
    }

    /**
     * 更新系统日志
     * @param array $data
     * @return SysLog
     */
    public static function updateSysLog(array $data): SysLog
    {
        $request_id = $data['request_id'];
        unset($data['request_id']);
        $return = json_encode($data, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
        return self::update(['return' => $return], ['request_id' => $request_id]);
    }

}




